<html>
<head>
  <meta charset="utf-8">
  <title>添加商品</title>
  <!-- 在移动端不缩放 -->
      <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
      <meta name="csrf-token" content="{{ csrf_token() }}">
      <title>导航条</title>
      <!-- 新 Bootstrap 核心 CSS 文件 -->

    @include('public.style')
</head>

	<body>

    @include('public.navbar')

	<form  id="login" name="login">
	<h3>上传素材</h1>

	<div class="layui-upload">
	  <button type="button" class="layui-btn" id="test2" style="font-size: 1.5rem;margin-top: 1rem;margin-bottom: 1rem;">多图片上传</button>
	  <blockquote class="layui-elem-quote layui-quote-nm">
	    预览图：<span>上传进度：</span><span id="percent">0</span><span>%</span><span id="newurl"></span>
	    <div class="layui-upload-list" id="demo2" style="margin-bottom: -1rem;" contenteditable="true"></div>
	 </blockquote>
	</div>


<div class="layui-form-item layui-form-text">
    <label class="layui-form-label">文案</label>
    <div class="layui-input-block">
      <textarea placeholder="请输入内容" class="layui-textarea" style="width: 90%;height: 30%;"></textarea>
    </div>
  </div>

  <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">补刀</label>
      <div class="layui-input-block">
        <textarea placeholder="请输入内容" class="layui-textarea" style="width: 90%;"></textarea>
      </div>
    </div>

 </form>
  <div class="layui-form-item">
      <div class="layui-input-block">

        <button class="layui-btn" onclick="submit()" style="height: 5rem;width: 10rem;">立即提交</button>
        <button class="layui-btn layui-btn-danger" onclick="sbzt()" style="height: 5rem;width: 10rem;">识别主图</button>
      </div>
    </div>

	@include('public.script')
	</body>
<script>
layui.use('upload', function(){
  var $ = layui.jquery
  ,upload = layui.upload;

  //多图片上传
  upload.render({
    elem: '#test2',
	accept: 'images,video',//允许上传的文件类型
	exts: 'jpg|png|gif|bmp|jpeg|mp4',
	// acceptMime:'image/jpg,image/png',
    url: '/user/upload_img', //改成您自己的上传接口
    multiple: true,//是否允许多文件上传
    headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
    before: function(obj){
      //预读本地文件示例，不支持ie8
      layer.load(); //上传loading
    }
    ,done: function(res){
      //上传完毕
      console.log(res);
      console.log(res.code);
	  if(res.code == 0){
		  layer.closeAll('loading'); //关闭loading
	        if(res.type == "video/mp4"){
				$('#demo2').append('<video src="'+ res.img_url +'" controls="controls" class="layui-upload-img">your browser does not support the video tag</video>')
			}else{
				$('#demo2').append('<img src="'+ res.img_url +'" class="layui-upload-img">')
			}


	      }else{
			  layer.msg(code.msg);
		  }
    }
  });


});
</script>
<script>

 //识别主图
function sbzt(){
	//var layer = layui.layer;
	//layer.msg("submit");
	var docment = document.getElementsByClassName('layui-textarea')[0].value;
	if(docment.length<=0){layer.msg("请输入带二合一文案");}
	else{
        $.ajax({
                type:"POST",
                url:"/user/discern_img",
                contentType: "application/json", //必须这样写
                dataType:"json",
                data:docment,
                headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                success:function (result) {
                    console.log(result);
                    if(result.code == 0){
                        $('#demo2').append('<img src="'+ result.imgurl +'" class="layui-upload-img">');
                        document.getElementsByClassName('layui-textarea')[0].value=result.docment;
                    }
                    layer.msg(result.msg);

                }

            })

	}

}
  //监听提交
function submit(){
    console.log('开始提交数据');
	//var layer = layui.layer;
	//layer.msg("submit");
	var docment = document.getElementsByClassName('layui-textarea')[0].value;
	var upcment = document.getElementsByClassName('layui-textarea')[1].value;
	var img_lenght = document.getElementsByClassName('layui-upload-img').length;
	if(docment.length<=0){layer.msg("请输入文案");}
	else if(img_lenght.length<=0){layer.msg("请上传图片");}
	else{
		var img_array = new Object();

		for(var i = 0;i<img_lenght;i++){
			img_array[i]=document.getElementsByClassName('layui-upload-img')[i].src;
		}
		console.log(img_array);//图片数组
		var goods_array = new Object;
		goods_array.img = img_array;
		goods_array.docment = Base64.encode(docment);
		if(upcment.length>0){goods_array.upcment = Base64.encode(upcment);}
		console.log(JSON.stringify(goods_array));
		$.ajax({
		        type:"POST",
		        url:"/user/goods_add",
		        contentType: "application/json", //必须这样写
		        dataType:"json",
		        data:JSON.stringify(goods_array),//将 JavaScript 值转换为 JSON 字符串
                headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
		        success:function (data) {
						console.log(data);
						console.log(data.code);
						if(data.code == 0){
							console.log("添加商品完毕");
							layer.msg("添加商品完毕");
							setTimeout(function () {
							    // 这里就是处理的事件
								location.reload();
							}, 1500);
						}else{
							layer.msg("添加商品失败");
						}

		        }

		    })



	}

}



</script>

<script type="text/javascript">
window.onload = function () {
	//绑定粘贴事件
	document.getElementById('demo2').onpaste = function () {
		paste_img(event);
		return false;
	};
}
function paste_img(e) {
    if (e.clipboardData && e.clipboardData.items) {
        var imageContent = e.clipboardData.getData('image/png');
        ele = e.clipboardData.items
        for (var i = 0; i < ele.length; ++i) {
        	//粘贴图片
            console.log(i);
            console.log(ele[i].kind);
            console.log(ele[i].type);
            console.log(ele[i]);
            if (ele[i].kind == 'file' && ele[i].type == 'image/png') {
                console.log('检测到图片');
                var blob = ele[i].getAsFile();
                window.URL = window.URL || window.webkitURL;
                var blobUrl = window.URL.createObjectURL(blob);

                /*
                // 显示到div中，此时是显示的本地图片数据，并没有上传到服务器
                var new_img = document.createElement('img');
                new_img.setAttribute('src', blobUrl);
                new_img.setAttribute('blobdata', blob);// 移动div光标到新元素后面
                insertHtmlAtCaret(new_img);// 直接上传，当然你也可以不在这上传，可以点击按钮在上传
                */

                uploadImg(blob);
            }                    //粘贴文本
            else{
            	// alert('没有图片');
				// layer.msg('没有图片');
            }
        }
    }
    else {
        alert('不支持的浏览器');
    }
}
//聊天内容框 插入文本或者其他元素后，移动置光标到最新处
function insertHtmlAtCaret(childElement) {
    var sel, range;
    if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            var el = document.createElement("div");
            el.appendChild(childElement);
            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }

            range.insertNode(frag);
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    }
    else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        //document.selection.createRange().pasteHTML(html);
    }
}
//前端上传方法
function uploadImg(obj) {
    //发送的数据
    var fd = new FormData();
    fd.append("file", obj, "imgtest.png");
    $.ajax({
        type: 'post',
        url: '/user/upload_img',
        data: fd,
        dataType: "json",
        contentType: false,// 当有文件要上传时，此项是必须的，否则后台无法识别文件流的起始位置(详见：#1)
        processData: false,// 是否序列化data属性，默认true(注意：false时type必须是post，详见：#2)
        headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
        xhr: xhrOnProgress(function(e){// (详见：#3)
            var percent= parseFloat(e.loaded) / e.total;//计算百分比
            $("#percent").html(parseInt(percent*100));
        }),
        success: function(data) {
            console.log(data);
            console.log(data.code);
            // 显示到div中
            // var new_img = document.createElement('img');
            // new_img.setAttribute('src', data.img_url);
            // insertHtmlAtCaret(new_img);// 直接上传，当然你也可以不在这上传，可以点击按钮在上传
            // $("#newurl").html(data.img_url);
			if(data.code == 0){
                console.log('append图片到demo2');
                $('#demo2').append('<img src="'+ data.img_url +'" class="layui-upload-img">');
            }else{
                alert(data.msg);
            }

        }
        ,error:function(e){
        	alert(e);
        }
    })
}
// 监听上传进度
var xhrOnProgress = function(fun) {
    xhrOnProgress.onprogress = fun; //绑定监听
    return function() {
        //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
        var xhr = $.ajaxSettings.xhr();
        //判断监听函数是否为函数
        if (typeof xhrOnProgress.onprogress !== 'function')
            return xhr;
        //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
        if (xhrOnProgress.onprogress && xhr.upload) {
            xhr.upload.onprogress = xhrOnProgress.onprogress;
        }
        return xhr;
    }
}
</script>


	</html>
